package top.lishuoboy.javaweb.a13cookie_session; /**
 * @author lishuoboy
 * @date 2022-01-09 17:34
 */

import cn.hutool.core.codec.Base64Encoder;
import lombok.extern.slf4j.Slf4j;
import top.lishuoboy.dependency.base.json.HuJsonUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebServlet(name = "CookieServlet", value = "/CookieServlet")
public class CookieServlet extends BaseServlet {
    /**
     * 获取cookies
     */
    protected void getCookie(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Cookie[] cookies = req.getCookies();
        String cookiesStr = HuJsonUtil.toJsonPrettyStr(cookies);
        log.debug("cookiesStr=={}", cookiesStr);
        resp.getWriter().write("<pre>" + cookiesStr + "</pre>");
    }

    /**
     * 创建cookie
     */
    protected void createCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // cookie的name不能是中文。名称必须遵守 RFC 2109。这意味着它只能包含 ASCII 字母数字字符，不能包含逗号、分号或空格，也不能以 $ 字符开头。cookie 的名称在创建之后不得更改。否则报错： Cookie name[一]是一个保留令牌
        // cookie的 value不支持 中文和特殊字符。如果使用二进制值，则可能需要使用 BASE64 编码。对于 Version 0 cookie，值不应包含空格、方括号、圆括号、等号、逗号、双引号、斜杠、问号、at 符号、冒号和分号。空值在所有浏览器上的行为不一定相同
        Cookie cookie1 = new Cookie("name1", "value1");
        Cookie cookie2 = new Cookie("name2", Base64Encoder.encode("value2硕"));
        cookie2.setMaxAge(10);
        cookie2.setComment("李硕测试2");

        log.info("创建cookie1=={}", HuJsonUtil.toJsonStr(cookie1));
        log.info("创建cookie2=={}", HuJsonUtil.toJsonStr(cookie2));

        resp.addCookie(cookie1);
        resp.addCookie(cookie2);

        // 第二种 创建cookie
        resp.addHeader("Set-Cookie", "name0=value0");
        resp.getWriter().write("createCookie成功");
    }

    /**
     * 更新cookie
     */
    protected void updateCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie cookie1 = new Cookie("name1", "value1111");
        log.info("修改cookie1=={}", HuJsonUtil.toJsonStr(cookie1));
        resp.addCookie(cookie1);
        resp.getWriter().write("修改Cookie成功");
    }

    /**
     * cookie生命周期
     * Cookie 的生命控制指的是如何管理 Cookie 什么时候被销毁（删除）
     * setMaxAge()  默认为 -1
     * 正数，表示在指定的秒数后过期
     * 负数，表示浏览器一关，Cookie 就会被删除（默认值是-1）
     * 零，表示马上删除 Cookie
     */
    protected void cookieLife(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie cookie1 = new Cookie("name1", "value1");
        Cookie cookie2 = new Cookie("name2", "value2");
        Cookie cookie3 = new Cookie("name3", "value3");
        Cookie cookie4 = new Cookie("name4", "value4");

        // 对应的响应头
        // Set-Cookie: name1=value1
        // Set-Cookie: name2=value2; Max-Age=0; Expires=Thu, 01-Jan-1970 00:00:10 GMT
        // Set-Cookie: name3=value3; Max-Age=10; Expires=Mon, 10-Jan-2022 08:39:28 GMT
        // Set-Cookie: name4=value4; Max-Age=2147483647; Expires=Sat, 28-Jan-2090 11:53:25 GMT
        cookie1.setMaxAge(-1);  // 默认值为 -1
        cookie2.setMaxAge(0);
        cookie3.setMaxAge(10);  // 10秒，短期存储
        cookie4.setMaxAge(Integer.MAX_VALUE);  // 长期存储

        resp.addCookie(cookie1);
        resp.addCookie(cookie2);
        resp.addCookie(cookie3);
        resp.addCookie(cookie4);

        resp.getWriter().write("创建4个不同周期的Cookie成功");
    }

    /**
     * cookie 有效路径
     */
    protected void cookiePath(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        log.debug(HuJsonUtil.toJsonPrettyStr(req.getCookies()));

        Cookie cookie1 = new Cookie("name1", "value1");
        Cookie cookie2 = new Cookie("name2", "value2");
        Cookie cookie3 = new Cookie("name3", "value3");

        String contextPath = this.getServletContext().getContextPath();
        log.debug(contextPath);

        // 对应的响应头
        // Set-Cookie: name1=value1; Path=/lishuoboy_javaweb_war_exploded
        // Set-Cookie: name2=value2; Path=/
        // Set-Cookie: name3=value3; Path=/lishuoboy_javaweb_war_exploded/aaa
        cookie1.setPath(contextPath);           // 默认值为 contextPath
        cookie2.setPath("/");
        cookie3.setPath(contextPath + "/lishuoboy");

        resp.addCookie(cookie1);
        resp.addCookie(cookie2);
        resp.addCookie(cookie3);

        resp.getWriter().write("创建3个不同path的Cookie成功");
    }

    /**
     * cookie 登录成功记住用户名，免输入用户名
     */
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name");
        String pwd = req.getParameter("pwd");
        if ("lishuo".equalsIgnoreCase(name) & "1".equals(pwd)) {
            Cookie cookie1 = new Cookie("name", name);
            cookie1.setMaxAge(30); // 30秒过期。真实环境可以设置时间长一点
            resp.addCookie(cookie1);
            req.getSession().setAttribute("loginMsg", "登录成功");
        } else {
            req.getSession().setAttribute("loginMsg", "登录失败");
        }
        resp.sendRedirect("13cookie_session/login_remember_name.jsp");
    }
}
